package com.chen.demo.netty.echo.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * echo服务端
 * 1.可以被多个channelHandler共享
 * 自定义事件处理器
 *
 * @author chenhongwei
 * @date 2019/2/17 16:54
 **/
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    private Logger logger = LoggerFactory.getLogger(EchoServerHandler.class);

    /**
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) ctx;
        //接受到的消息打印到控制台
        logger.info("Server received:{}", in.toString(CharsetUtil.UTF_8));
        //接受到的消息发送给发送者
        ctx.write(in);
        super.channelRead(ctx, msg);
    }

    /**
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("EchoServerHandler 异常", cause);
        //关闭连接
        ctx.close();
        super.exceptionCaught(ctx, cause);
    }
}
